package com.enniswu.weitter.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.enniswu.weitter.R;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.text.InputType.TYPE_CLASS_NUMBER;
import static android.text.InputType.TYPE_CLASS_PHONE;
import static android.text.InputType.TYPE_CLASS_TEXT;
import static android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE;
import static android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD;

public class TextEditView extends LinearLayout {

    @BindView(R.id.tv_key)
    TextView tvKey;
    @BindView(R.id.et_value)
    EditText etValue;

    public TextEditView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.widget_text_edit, this, true);
        ButterKnife.bind(this, this);
        setOrientation(HORIZONTAL);
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.TextEditView);
        if (attributes != null) {
            tvKey.setText(attributes.getText(R.styleable.TextEditView_TEV_text));
            etValue.setHint(attributes.getText(R.styleable.TextEditView_TEV_hint));
            etValue.setMaxLines(attributes.getInt(R.styleable.TextEditView_TEV_maxLines, 1));
            int maxLength = attributes.getInt(R.styleable.TextEditView_TEV_maxLength, 16);
            InputFilter[] filters = { new InputFilter.LengthFilter(maxLength) };
            etValue.setFilters(filters);
            int inputType = attributes.getInt(R.styleable.TextEditView_TEV_inputType, 0);
            switch (inputType) {
                case 0:
                    etValue.setInputType(TYPE_CLASS_TEXT);
                    break;
                case 1:
                    etValue.setInputType(TYPE_TEXT_FLAG_MULTI_LINE);
                    break;
                case 2:
                    etValue.setInputType(TYPE_CLASS_PHONE);
                    break;
                case 3:
                    etValue.setInputType(TYPE_CLASS_NUMBER);
                    break;
                case 4:
                    etValue.setInputType(TYPE_TEXT_VARIATION_PASSWORD);
                    break;
            }
            attributes.recycle();
        }
    }

    public void setText(CharSequence text) {
        etValue.setText(text);
    }

    public Editable getText() {
        return etValue.getText();
    }
}
